Ext.namespace('Xadmin');

/**
 * @class Xadmin.RESTGrid
 * @extends Ext.superclass
 * @constructor
 *
 * @param {Object}
 *            config The configuration options
 */
Xadmin.RESTGrid = function(config) {
	//RowActions
	this.bbar = '';
	//Search Text
	this.searchText = 'Buscar';
	this.searchTipText = 'Entre un texto y presione enter.';
	this.selectAllText = 'Seleccionar Todos';
	this.messageText = 'Mensaje';
	this.deleteText = 'Esta seguro que desea eliminar el item?';
	this.createText = 'Agregar';
	this.createTipText = 'Agregar item al riesgo';
	this.createFailureText = 'El elemento no pudo ser creado.';
	this.updateFailureText = 'El elemento no pudo ser editado.';
	this.deleteFailureText = 'El elemento no pudo ser eliminado.';
	this.updateText = 'Editar';
	this.resourceUrl = '';
	this.resource = '';
	this.conn = new RestHandler.Connection();
	this.creating = false;
	this.updating = false;
	this.recordForm = new Ext.ux.grid.RecordForm({
		  title : this.updateText
		, iconCls : 'icon-edit-record'
		, columnCount : 2
		, ignoreFields : {
			action1 : true
		}, formConfig : {
			  labelWidth : 80
			, buttonAlign : 'right'
			, bodyStyle : 'padding-top:10px'
		}
	});
	this.recordForm.onOK = function () {
		this.window.hide(null);
		if (this.grid.creating) {
			this.grid.conn.on('requestexception', function(conn, response, opt) {
					this.grid.recordForm.onCancel();
					Ext.MessageBox.alert(this.grid.messageText, this.grid.createFailureText);
				}, this);
			this.grid.conn.create(this.grid.resourceUrl, this.grid.resource2XML(this.form.getForm().getValues()), {
				scope: this
				, success: function(response) {
						this.scope.updateRecord();
						var responseTxt =response.response.responseText;
						var a = responseTxt.split('/');
						var resourceId = a[a.length - 1];
						this.scope.record.id = resourceId;
					}
			});
			this.grid.creating = false;
		} else {
			this.grid.update(this.grid, this.record, this.form.getForm().getValues());
		}
	}

	this.tbar = ['->', {
		text : this.createText
		, tooltip : this.createTipText
		, iconCls : 'icon-add'
		, listeners:{
					click:{scope:this, buffer:200, fn:function(btn) {
						this.creating = true;
						this.recordForm.title = this.createText;
						this.recordForm.show(this.addRecord(), btn.getEl());
					}}
				}
	}];
	this.listeners = {
		render : function(g) {
			var ddrow = new Ext.ux.dd.GridReorderDropTarget(g, {
				copy : false,
				listeners : {
					beforerowmove : function(objThis, oldIndex, newIndex,
							records) {
						// code goes here
						// return false to cancel the move
					},
					afterrowmove : function(objThis, oldIndex, newIndex,
							records) {
						// code goes here
					},
					beforerowcopy : function(objThis, oldIndex, newIndex,
							records) {
						// code goes here
						// return false to cancel the copy
					},
					afterrowcopy : function(objThis, oldIndex, newIndex,
							records) {
						// code goes here
					}
				}
			});
			Ext.dd.ScrollManager.register(g.getView().getEditorParent());
		},
		beforedestroy : function(g) {
			Ext.dd.ScrollManager.unregister(g.getView().getEditorParent());
		}
	};
	this.plugins = [new Ext.ux.grid.Search({
			  mode : 'local'
			, iconCls : false
			, dateFormat : 'm/d/Y'
			, readonlyIndexes : []
			, disableIndexes : []
			, minLength : 2
			, position : 'top'
			, width: 200
			, searchText : this.searchText
			, searchTipText : this.searchTipText
			, selectAllText : this.selectAllText
		}), this.rowActions, this.recordForm]
	var config = config || {};
	Xadmin.RESTGrid.superclass.constructor.call(this, config);
	this.on({
        afteredit:{scope:this, fn:function(e) {
            this.update(e.grid, e.record, e.record.data, true);
        }}
    });
}

Ext.extend(Xadmin.RESTGrid, Ext.grid.EditorGridPanel, {
	  id : 'tasks-grid'
	, ddGroup : 'testDDGroup'
	, enableDragDrop : true
	, height : 500
	, layout : 'fit'
	, frame : true
	, collapsible : true
	, iconCls : 'icon-grid'
	, enableColumnHide : false
	, enableColumnMove : false
	, addRecord : function() {
		var store = this.store;
		if(store.recordType) {
			var rec = new store.recordType({newRecord:true});
			rec.fields.each(function(f) {
				rec.data[f.name] = f.defaultValue || null;
			});
			rec.commit();
			store.add(rec);
			return rec;
		}
		return false;
	}
	, deleteItem : function(record) {
        Ext.MessageBox.confirm(this.messageText, this.deleteText , this.deleteRecord, this);
	},
	deleteRecord: function(btn) {
		if(btn == 'yes') {
			var m = this.getSelectionModel().getSelected();
			this.conn.on('requestexception', function(conn, response, opt) {
						Ext.MessageBox.alert(this.messageText, this.deleteFailureText);
					}, this);
			this.conn.deleteResource(this.resourceUrl + '/' + m.id, {
				scope: this
				, success: function() {
						var m = this.scope.getSelectionModel().getSelected();
						this.scope.getStore().remove(m);
					}
			});
		}
	},
	onRowAction : function(grid, record, action, row, col) {
		switch (action) {
			case 'icon-delete' :
				this.deleteItem(record);
				break;
			case 'icon-edit-record' :
				this.updating = true;
				this.recordForm.title = this.updateText;
				this.recordForm.show(record, grid.getView().getCell(row, col));
				break;
		}
	}
	, resource2XML : function(record) {
		var resourceXML = '<?xml version="1.0" encoding="UTF-8" ?>';
		resourceXML += '<' + this.resource + '>';
		for (var keyName in record) {
			value = record[keyName];
			if(!Ext.type(value) || Ext.type(value) == 'object')
				value = value.format('Y-m-d')
			resourceXML += '<' + keyName + '>' + value + '</' + keyName + '>';
		}
		resourceXML += '</' + this.resource + '>';
		return resourceXML;
	}
	, onRender : function() {
		Xadmin.RESTGrid.superclass.onRender.apply(this, arguments);
		this.getStore().load({params:{start : 0, limit : 25}});

	}
	, update : function(grid, record, newRecord, inline) {
		grid.conn.on('requestexception', function(conn, response, opt) {
				Ext.MessageBox.alert(grid.messageText, grid.updateFailureText);
			}, this);
		var updateUrl = grid.resourceUrl + '/' + record.id;
		grid.conn.update(updateUrl, grid.resource2XML(newRecord), {
			scope: this
			, success: function(response) {
					if (!inline)
						this.scope.recordForm.updateRecord();
				}
		});
		grid.updating = false;
	}
	, boldRenderer : function(value, p, record) {
			return String.format('<b>{0}</b>', value);
	}
});

//Ext.namespace('Xadmin.ProjectGrid');

/**
 * @class Xadmin.ProjectGrid
 * @extends RESTGrid
 * @constructor
 *
 * @param {Object} config The configuration options
 */
Xadmin.ProjectGrid = function(config) {

	this.title = 'Proyectos';
	this.resourceUrl = '/projects'
	this.resource = 'project'
	this.reader = new Ext.data.XmlReader({
               record: 'project',
               id: '@id'
           }, [
               'name',
			   'client',
               'description',
			   {name:'start', type: 'date', dateFormat: 'Y-m-d'},
			   {name: 'end', type: 'date', dateFormat: 'Y-m-d'}
			   , {name : 'action1', type : 'string'}
           ]);
	this.ds = new Ext.data.GroupingStore({
		  url : this.resourceUrl
		, proxy : new Ext.data.HttpProxy({url : this.resourceUrl, method : 'get'})
		, reader : this.reader
		, sortInfo : { field : 'name', direction : "ASC" }
//		, groupField:'client'
	});
	this.sm = new Ext.grid.RowSelectionModel({ singleSelect : true });
	this.view = new Ext.grid.GroupingView({
		  forceFit : true
		, ignoreAdd : true
		, groupTextTpl : '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
		, emptyText : 'No hay proyectos.'
	});
	this.rowActions = new Ext.ux.grid.RowActions({
		header : this.actionsText,
		actions : [
		{
			  iconCls : 'icon-edit-record'
			, qtip : 'Editar item'
		}
		, {
			  iconCls : 'icon-delete'
			, qtip : 'Eliminar'
		}],
		widthIntercept : Ext.isSafari ? 4 : 2,
		id : 'actions'
	});
	this.rowActions.on('action', this.onRowAction, this);
	var config = config || {
		renderTo : 'risk-grid'
		, resourceUrl: '/projects'
		, resource: 'project'
		, cm : new Ext.grid.ColumnModel([
			{header: "Nombre", width: 200, dataIndex: 'name', editor: new Ext.form.TextField({allowBlank: false}), renderer: this.boldRenderer},
			{header: "Cliente", dataIndex: 'client', editor: new Ext.form.TextField({allowBlank: false})},
			{header: "Descripcion", width: 300, dataIndex: 'description', editor: new Ext.form.TextArea({allowBlank: false})},
			{header: "Inicio", dataIndex: 'start', renderer: Ext.util.Format.dateRenderer('Y-m-d'), editor: new Ext.form.DateField({format: 'Y-m-d'})},
			{header: "Fin", dataIndex: 'end', renderer: Ext.util.Format.dateRenderer('Y-m-d'), editor: new Ext.form.DateField({format: 'Y-m-d'})}
			, this.rowActions
		])
		, bbar : new Ext.PagingToolbar({
        pageSize: 15,
        store: this.ds,
        displayInfo: true
    	})
	};
	Xadmin.ProjectGrid.superclass.constructor.call(this, config);
}

Ext.extend(Xadmin.ProjectGrid, Xadmin.RESTGrid, {});

//Ext.reg('xtype', Ext.ux.Xadmin.ProjectGrid);

